package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import org.apache.catalina.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {
    @RequestMapping("leaf")
    public String thymeleafPress(HttpServletRequest request){
        request.setAttribute("name","张三");
        request.setAttribute("grade",80);
        List<UserBean> list = List.of(
                new UserBean(1,"李关明", LocalDate.parse("1997-11-11"),8000),
                new UserBean(2,"张关明", LocalDate.parse("1998-11-28"),7000),
                new UserBean(3,"刘关明", LocalDate.parse("1998-10-20"),7500)
        );
        request.setAttribute("list",list);
        return  "/leaf.html";
    }


    @RequestMapping("add")
    @ResponseBody
    public String add(@Valid UserBean user, BindingResult result) throws JsonProcessingException {
        if (result.hasErrors()){
            //得到所有的错误信息
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            return om.writeValueAsString(errorList);
        }

        System.out.println("执行添加操作");
        return "ok";
    }
}
